package com.study.spmongodb.wwj;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/15 22:49
 * https://www.bilibili.com/video/BV1hJ411D7k2?p=37
 */
public class SimpleThreadPool {
    private final int size;
    private final static int DEAFULT_TASK_QUEUE_SIZE = 2000;
    private final int queueSize;
    private final static int DEFAULT_SIZE = 10;
    private static volatile int seq = 0;
    private final static String THREAD_PREFIX = "SIMPLE_THREAD_POOL_";
    private final static ThreadGroup GROUP = new ThreadGroup("Poool-Group");
    /**
     * 任务队列
     */
    private final static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>();

    private final static ArrayList<WorkerTask> THREAD_QUEUE = new ArrayList<>();

    private final DiscardPolicy discardPolicy;

    public SimpleThreadPool() {
        this(DEFAULT_SIZE, DEAFULT_TASK_QUEUE_SIZE, () -> {
            throw new DiscardException("超出size");
        });
    }

    public SimpleThreadPool(int size, int queueSize, DiscardPolicy discardPolicy) {
        this.size = size;
        this.queueSize = queueSize;
        this.discardPolicy = discardPolicy;
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        for (int i = 0; i < size; i++) {
            createWorkTask();
        }
    }

    public void submit(Runnable runnable) throws DiscardException {
        synchronized (TASK_QUEUE) {
            if (TASK_QUEUE.size() > queueSize) {
                discardPolicy.discard();
            }
            TASK_QUEUE.addLast(runnable);
            TASK_QUEUE.notifyAll();
        }
    }

    private void createWorkTask() {
        final WorkerTask task = new WorkerTask(GROUP, THREAD_PREFIX + (seq++));
        task.start();
        THREAD_QUEUE.add(task);
    }


    /**
     * 线程状态
     */
    private enum TaskState {
        FREE, RUNNING, BLICKED, DEAD
    }

    /**
     * 拒绝策略
     */
    public interface DiscardPolicy {
        void discard() throws DiscardException;
    }

    /**
     * 拒绝异常
     */
    public static class DiscardException extends Exception {
        public DiscardException(String msg) {
            super(msg);
        }
    }

    private static class WorkerTask extends Thread {
        private volatile TaskState taskState = TaskState.FREE;

        public WorkerTask(ThreadGroup group, String name) {
            super(group, name);
        }

        public TaskState getTaskState() {
            return taskState;
        }

        @Override
        public void run() {
            OUTER:
            while (this.taskState != TaskState.DEAD) {
                Runnable runnable = null;
                synchronized (TASK_QUEUE) {
                    while (TASK_QUEUE.isEmpty()) {
                        try {
                            taskState = TaskState.BLICKED;
                            TASK_QUEUE.wait();
                        } catch (InterruptedException e) {
                            break OUTER;
                        }
                    }
                    runnable = TASK_QUEUE.removeFirst();
                }
                if (null != runnable) {
                    taskState = TaskState.RUNNING;
                    runnable.run();
                    taskState = TaskState.FREE;
                }
            }
        }

        public void close() {
            this.taskState = TaskState.DEAD;
        }
    }

    public static void main(String[] args) throws InterruptedException, DiscardException {
        final SimpleThreadPool threadPool = new SimpleThreadPool(10, 15, () -> {
            throw new DiscardException("超出size");
        });
        for (int i = 0; i < 40; i++) {
            int finalI = i;
            threadPool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " <> " + finalI);
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
